using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Net.Sockets;

namespace Space_Conquest
{

    /// <summary>
    /// Connects to a Server, and sends messages back and forth
    /// </summary>
    public class Client : SocketConnection
    {

        #region Private Members

        string m_serverIP;
        bool m_isConnected;

        #endregion

        #region Properties

        public string ServerIP
        {
            get
            {
                return m_serverIP;
            }
        }

        public bool IsConnected
        {
            get
            {
                return m_isConnected;
            }
        }

        #endregion

        #region Constructors

        public Client(string serverIPAddress) :
            this(serverIPAddress, 2344)
        {
        }

        public Client(string serverIPAddress, int portNumber) :
            base()
        {

            if (serverIPAddress == "localhost")
                serverIPAddress = "127.0.0.1";

            m_isConnected = false;
            m_serverIP = serverIPAddress;
            m_port = portNumber;

            OnConnectionError += new ConnectionErrorEventHandler(SimpleClient_OnConnectionError);

            ConnectToServer();

        }

        #endregion

        #region Methods

        public void AttemptReconnect()
        {

            if (!m_isConnected)
            {
                ConnectToServer();
            }

        }

        void ConnectToServer()
        {

            try
            {

                IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(m_serverIP), m_port);
                m_mainSocket.Connect(ipEndPoint);

                if (m_mainSocket.Connected)
                {
                    m_isConnected = true;
                    WaitForMeta(m_mainSocket);
                }

            }
            catch
            {
                Console.WriteLine("Failed to connect to server at: " + m_serverIP +
                                  ", on port: " + m_port.ToString());
            }

        }

        void SimpleClient_OnConnectionError(Socket source)
        {

            m_isConnected = false;
            m_mainSocket.Close();
            m_mainSocket = null;
            m_mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        }

        public override void SendData(object obj)
        {
            if (m_isConnected)
            {
                try
                {

                    m_mainSocket.Send(FullSerialize(obj));

                }
                catch
                {
                    m_isConnected = false;
                }
            }
        }

        #endregion

    }
}
